package com.qf.controller;

import com.alibaba.fastjson.JSON;
import com.qf.dto.UserDto;
import com.qf.pojo.User;
import com.qf.service.Impl.UserServiceImpl;
import com.qf.service.UserService;


import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.HashMap;

@WebServlet(name = "userRegisterController", value = "/userRegisterController.action")
public class UserRegisterController extends HttpServlet {
    private UserService userService = new UserServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String password2 = req.getParameter("password2");

        UserDto userDto = new UserDto();
        userDto.setUsername(username);
        userDto.setPassword(password);
        HashMap<String, Object> maps = new HashMap<>();
        if (password.equals(password2)) {
            User user = userService.login(userDto);
            if (user != null) {
                maps.put("message", "用户名已存在");
                resp.getWriter().write(JSON.toJSONString(maps));
            }else {
                if (userService.insert(userDto)) {
                    maps.put("state", 200);
                    resp.getWriter().write(JSON.toJSONString(maps));
                } else {
                    maps.put("message", "用户名已存在");
                    resp.getWriter().write(JSON.toJSONString(maps));
                }
            }
        } else {
            maps.put("message", "注册失败，两次密码不正确");
            resp.getWriter().write(JSON.toJSONString(maps));
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}
